
clear all;
close all;

A = { "gsl_ext_conjgrad_fr_mt", "gsl_ext_conjgrad_pr_mt" };
TF = GSLpp_testfunctions();

TITLES = { "Fletcher-Reeves", "Polak-Ribiere" };
FN_SUFFIXES = { "fr", "pr" };

for ai = 1:2
  x0 = GSLpp_get_startingpoint(TF{12}.starting_point, 60);
  xmin = GSLpp_get_minimizer(TF{12}.minimizer, 60);

  results = GSLpp_minimize(A{ai}, struct, struct, ...
                           "extendedrosenbrock", struct("n", 60), ...
                           struct("f", "sym", "g", "sym", "H", "sym"), ...
                           "xdisttomin", struct("eps", 1e-8, "xmin", xmin), ...
                           x0, 0, false);

  gradnorms = ones(results.numiter, 1);
  cosangles = ones(results.numiter, 1);
  dnorms = ones(results.numiter, 1);

  for k = 1:results.numiter
    g = results.iterations{k}.g;
    d = results.iterations{k}.d;
    gd = -g'*d;
    gradnorms(k) = norm(g);
    cosangles(k) = gd / (norm(g) * norm(d));
    dnorms(k) = norm(d);
  endfor

  GSLpp_newplot();

  hold on;
  semilogy(1:results.numiter, cosangles, "-r", "linewidth", 6);
  semilogy(1:results.numiter, gradnorms, "-b", "linewidth", 6);
  semilogy(1:results.numiter, dnorms, "-g", "linewidth", 6);
  semilogy(0:results.numiter, ones(1, results.numiter + 1), "-k");
  hold off;

  title(TITLES{ai});
  legend('cos\theta', '||\nabla f(x)||', '||d||');
  legend("boxon");
  xlabel("iterations");

  axis([ 1, min(results.numiter, 90), 1e-3, 8000 ]);
  print([ "conjgrad_test_extendedrosenbrock_", FN_SUFFIXES{ai}, ".ps" ], "-landscape", "-dashed", "-FArial:22");
  close;
endfor
